package com.projectpractice.controller;


import com.projectpractice.bean.Article;
import com.projectpractice.bean.Classify;
import com.projectpractice.bean.User;
import com.projectpractice.service.ArticleService;
import com.projectpractice.service.ClassifyService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController

public class PortalController {
    @Autowired
    ArticleService articleService;
    @Autowired
    ClassifyService classifyService;

    @RequestMapping("/portal_index")
    public ModelAndView toIndex(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("portal_index");
        List<Article> articles=articleService.getArticles();
        mv.addObject("articles",articles);
        List<Classify> classifies=classifyService.getClassify();
        mv.addObject("classifies",classifies);
        if(SecurityUtils.getSubject().getPrincipal()!=null){
            mv.addObject( "user",(User) SecurityUtils.getSubject().getPrincipal());
        }else {
            mv.addObject( "user",new User());
        }
        return mv;
    }

    @RequestMapping("/portal_detail/{id}")
    public ModelAndView toIndex(@PathVariable Integer id){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("portal_detail");
        Article article=articleService.getArticleById(id);
        mv.addObject("article",article);
        List<Classify> classifies=classifyService.getClassify();
        mv.addObject("classifies",classifies);
        if(SecurityUtils.getSubject().getPrincipal()!=null){
            mv.addObject( "user",(User) SecurityUtils.getSubject().getPrincipal());
        }else {
            mv.addObject( "user",new User());
        }
        return mv;
    }

    @RequestMapping("/logout")
    public ModelAndView logout() {
        ModelAndView mv = new ModelAndView();
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        mv.setViewName("portal_login");
        return mv;
    }
}
